import { useState } from 'react';
import { uploader } from '../api/upload';
import { Toast } from '@douyinfe/semi-ui';

/**
 * 图片编辑专用的上传 Hook
 * @param {Object} options - 配置选项
 * @param {Function} options.onSuccess - 上传成功回调
 * @param {Function} options.onError - 上传失败回调
 * @returns {Object} - 返回上传相关的状态和方法
 */
export const useVideoUpload = (options = {}) => {
    const { onSuccess, onError } = options;
    
    const [uploading, setUploading] = useState(false);
    const [progress, setProgress] = useState(0);
    const [uploadedFile, setUploadedFile] = useState(null);
    
    /**
     * 获取视频尺寸信息
     * @param {File} file - 视频文件
     * @returns {Promise<Object>} - 包含width和height的对象
     */
    const getVideoDimensions = (file) => {
        return new Promise((resolve, reject) => {
            const video = document.createElement('video');
            const url = URL.createObjectURL(file.fileInstance);
            video.onloadedmetadata = () => {
                const dimensions = {
                    width: video.videoWidth,
                    height: video.videoHeight
                };
                // 延迟释放URL，确保视频元素完全加载
                setTimeout(() => {
                    URL.revokeObjectURL(url);
                }, 100);
                resolve(dimensions);
            };
            
            video.onerror = () => {
                URL.revokeObjectURL(url);
                reject(new Error('无法获取视频尺寸'));
            };
            
            video.src = url;
        });
    };

    /**
     * 上传视频文件
     * @param {File} file - 要上传的文件
     * @param {string} fileName - 自定义文件名（可选）
     * @returns {Promise<Object>} - 上传结果，包含视频尺寸信息
     */
    const handleUpload = async (file, fileName) => {
        if (!file) {
            const error = new Error('请选择要上传的文件');
            onError?.(error);
            Toast.error('请选择要上传的文件');
            return { success: false, error };
        }
        
        setUploading(true);
        setProgress(0);
        
        try {
            // 获取视频尺寸信息
            console.log('正在获取视频尺寸信息...');
            const videoDimensions = await getVideoDimensions(file);
            console.log('视频尺寸信息:', videoDimensions);
            
            // 模拟上传进度
            const progressInterval = setInterval(() => {
                setProgress(prev => {
                    if (prev >= 90) {
                        clearInterval(progressInterval);
                        return 90;
                    }
                    return prev + 10;
                });
            }, 100);
            
            // 执行上传
            const result = await uploader(file, fileName);
            
            clearInterval(progressInterval);
            setProgress(100);
            
            if (result.success) {
                // 将视频尺寸信息添加到结果中
                const enhancedResult = {
                    ...result,
                    // videoDimensions
                };
                
                setUploadedFile({
                    file,
                    url: result.url,
                    fileName: result.fileName,
                    // videoDimensions
                });
                
                onSuccess?.(enhancedResult);
                Toast.success('视频上传成功');
                
                return enhancedResult;
            } else {
                throw new Error('上传失败');
            }
            
        } catch (error) {
            console.error('视频上传失败:', error);
            
            onError?.(error);
            Toast.error(error.message || '视频上传失败');
            
            return { success: false, error };
            
        } finally {
            setUploading(false);
            // 延迟重置进度条
            setTimeout(() => {
                setProgress(0);
            }, 1000);
        }
    };
    
    /**
     * 重置上传状态
     */
    const resetUpload = () => {
        setUploading(false);
        setProgress(0);
        setUploadedFile(null);
    };
    
    /**
     * 验证文件是否符合要求
     * @param {File} file - 要验证的文件
     * @returns {Promise<boolean>} - 验证结果
     */
    const validateFile = async (file) => {
        // 验证视频
        const actualFile = file.fileInstance || file;
        
        // 检查文件大小（2GB限制）
        const maxSize = 2 * 1024 * 1024 * 1024; // 2GB
        if (actualFile.size > maxSize) {
            Toast.error('视频大小不能超过2GB');
            return false;
        }
        
        return true;
    };
    
    return {
        // 状态
        uploading,
        progress,
        uploadedFile,
        
        // 方法
        handleUpload,
        resetUpload,
        validateFile
    };
};

export default useVideoUpload;